import { login, getComList, getMenus } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const comCache = sessionStorage.getItem('selectCom') || '{}';
const com = JSON.parse(comCache);
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  comId: com.pkid || null,
  comName: com.name || null,
  comList: null,
  menuList: null,
  flag: false,
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_COM: (state, id) => {
    state.comId = id
  },
  SET_COM_NAME: (state, name) => {
    state.comName = name
  },
  SET_COM_LIST: (state, comList) => {
    state.comList = comList
  },
  SET_MENU_LIST: (state, menuList) => {
    state.menuList = menuList;
  },
  SET_FLAG: (state) => {
    state.flag = true;
  },
  CLEAR_STATE: (state) => {
    state.token = null;
    state.name = '';
    state.avatar = '';
    state.introduction = '';
    state.roles = [];
    state.comId = null;
    state.comName = null;
    state.comList = null;
    state.menuList = null;
    state.flag = false;
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, isSave } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const data = response
        commit('SET_TOKEN', data.access_token)
        setToken(data.access_token, isSave)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ dispatch, commit, state }) {
    return Promise.all([getMenus(), getComList()]).then(data => {
      const [menuList, com] = data;
      commit('SET_MENU_LIST', menuList);
      commit('SET_COM_LIST', com);
      commit('SET_FLAG');
      if (!state.comId) {
        dispatch('setCom', com[0]);
      }
      return { menuList, comList: com };
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken()
      resetRouter()
      commit('CLEAR_STATE');
      sessionStorage.clear()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  setCom({ commit }, com) {
    if (!com) {
      sessionStorage.removeItem('selectCom');
      commit('SET_COM', null);
      commit('SET_COM_NAME', null);
      return
    }
    sessionStorage.setItem('selectCom', JSON.stringify(com));
    commit('SET_COM', com.pkid);
    commit('SET_COM_NAME', com.name);
  },
  // getComList({ dispatch, commit, state }) {
  //   return getComList().then(res => {
  //     if (res.code === 1) {
  //       commit('SET_COM_LIST', res.data);
  //       const com = res.data[0];
  //       if (!state.comId) {
  //         dispatch('setCom', com)
  //       }
  //       return res.data;
  //     } else {
  //       throw res.msg;
  //     }
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
